<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Article;
use App\Category;
use App\Comment;
use DB;

class ArticleController extends Controller
{
    function index(){
        $article_num=DB::table('articles')->count();
        $comment_num=DB::table('comments')->count();
        $view_num=DB::table('articles')->sum('view');
        $articles=Article::with('category')->with('comment')->get();

        return view('articles.index')->with([
            'articles'=>$articles,
            'comment_num'=>$comment_num,
            'view_num'=>$view_num,
            'article_num'=>$article_num
        ]);
    }

    function create(){
        $categories=Category::all();
        return view('articles.create')->with('categories',$categories);
    }

    function store(Request $request){
        Article::create($request->all());
        return redirect(route('articles.index'));
    }

    function edit($id){
        $article=Article::find($id);
        $categories=Category::all();
        return view('articles.edit')
            ->with('article',$article)
            ->with('categories',$categories);
    }

    function update($id,Request $request){
        $article=Article::find($id);
        $article->update($request->all());
        return redirect(route('articles.index'));
    }

    function show($id){
        $article=Article::with('category')->with('comment')->find($id);
        DB::table('articles')->where('id',$id)->increment('view', 1);
        return view('articles.show')->with('article',$article);
    }
    
    function add_c(Request $request){
        Comment::create($request->all());
        return redirect()->route('articles.show',$request->article_id);
    }
}
